<?php
//CHANGE INDEX __construct
if (!defined('BASEPATH'))
   exit('No direct script access allowed');
session_start();
class Contest extends MX_Controller {

   private $module = 'contest';
   private $table = 'contest';

   function __construct() {
      parent::__construct();
      $this->load->model($this->module . '_model', 'model');
      if ($this->uri->segment(1) == 'admincp') {
         if ($this->uri->segment(2) != 'login') {
            if (!$this->session->userdata('userInfo')) {
               header('Location: ' . PATH_URL . 'admincp/login');
               return false;
            }
         }
         $this->template->set_template('admin');
         $this->template->write('title', 'Admin Control Panel');
      }else {
         if($_SESSION['profile'] == ""){
           require 'application/libraries/facebook.php';
           $facebook = new Facebook(array('appId'  => FB_APP_ID, 'secret' => FB_SECRET));
           $signed_request = $facebook->getSignedRequest();
           $user_profile = $facebook->api('/me');
          
           $_SESSION['profile'] =  $user_profile;
           $_SESSION['fb_id']= $signed_request['user_id'];
           } 
      } 
   }

   /* ------------------------------------ Admin Control Panel ------------------------------------ */

   public function admincp_index() {
      $default_func = 'created';
      $default_sort = 'DESC';

      $data = array(
          'module' => $this->module,
          'default_func' => $default_func,
          'default_sort' => $default_sort,
          'weeks' => $this->model->get_list_weeks()
      );
       
      $this->template->write_view('content', 'BACKEND/index', $data);
      $this->template->render();
   }


   public function admincp_save() {
      //Upload Image
      $fileName = array('image' => '');
            if ($_FILES) {
                foreach ($fileName as $k => $v) {
                    if (isset($_FILES['fileAdmincp']['error'][$k])) {
                        $typeFileImage = strtolower(substr($_FILES['fileAdmincp']['type'][$k], 0, 5));
                        if ($typeFileImage == 'image' || $typeFileImage == 'video') {
                            $tmp_name[$k] = $_FILES['fileAdmincp']["tmp_name"][$k];
                            $file_name[$k] = $_FILES['fileAdmincp']['name'][$k];
                            $ext = strtolower(substr($file_name[$k], -4, 4));
                            if ($ext == 'jpeg') {
                                $fileName[$k] = time() . '_' . SEO(substr($file_name[$k], 0, -5)) . '.jpg';
                            } else {
                                $fileName[$k] = time() . '_' . SEO(substr($file_name[$k], 0, -4)) . $ext;
                            }
                        } else {
                            print 'Only upload Image.';
                            exit;
                        }
                    }
                }
            }
      //End Upload Image

      if ($this->model->saveManagement($fileName)) {
         //Upload Image
         if ($_FILES) {
            if (isset($_FILES['fileAdmincp']['error'])) {
                 foreach ($fileName as $k => $v) {
                   $upload_path = BASEFOLDER . 'static/uploads/contest/';
                     move_uploaded_file($tmp_name[$k], $upload_path . $fileName[$k]);
                 }
            }
         }
         //End Upload Image
         print 'success';
         exit;
      }
   }

   public function admincp_update($id = 0) {
      $result[0] = array();
      if ($id != 0) {
         $result = $this->model->getDetailManagement($id);
      }
      $data = array(
          'result' => $result[0],
          'module' => $this->module,
          'id' => $id,
          'users' => $this->model->list_users(),
          'province' => $this->model->get_province(),
      );
      $this->template->write_view('content', 'BACKEND/ajax_editContent', $data);
      $this->template->render();
   }

   public function admincp_delete() {
      if ($this->input->post('id')) {
         $id = $this->input->post('id');
         $result = $this->model->getDetailManagement($id);
         $this->db->where('id', $id);
         if ($this->db->delete(PREFIX . $this->table)) {
            return true;
         }
      }
   }

   public function admincp_ajaxLoadContent() {
	
      $this->load->library('AdminPagination');
      $config['total_rows'] = $this->model->getTotalsearchContent();
      $config['per_page'] = $this->input->post('per_page');
      $config['num_links'] = 3;
      $config['func_ajax'] = 'searchContent';
      $config['start'] = $this->input->post('start');
      $this->adminpagination->initialize($config);

      $result = $this->model->getsearchContent($config['per_page'], $this->input->post('start'));
    
      $data = array(
          'result' => $result,
          'per_page' => $this->input->post('per_page'),
          'start' => $this->input->post('start'),
          'module' => $this->module
      );
      $this->session->set_userdata('start', $this->input->post('start'));
      
      $this->load->view('BACKEND/ajax_loadContent', $data);
   }

   public function admincp_ajaxUpdateWinnerStatus() {
      if ($this->input->post('winner') == 0) {
         $winner = 1;
      } else {
         $winner = 0;
      }
      $data = array(
          'is_winner' => $winner
      );
      $this->db->where('id', $this->input->post('id'));
      $this->db->update(PREFIX . $this->table, $data);

      $update = array(
          'is_winner' => $winner,
          'id' => $this->input->post('id'),
          'module' => $this->module
      );
      $this->load->view('BACKEND/ajax_updateWinnerStatus', $update);
   }

   public function admincp_ajaxUpdateStatus() {
      if ($this->input->post('status') == 0) {
         $status = 1;
      } else {
         $status = 0;
      }
      $data = array(
          'status' => $status
      );
      $this->db->where('id', $this->input->post('id'));
      $this->db->update(PREFIX . $this->table, $data);

      $update = array(
          'status' => $status,
          'id' => $this->input->post('id'),
          'module' => $this->module
      );
      $this->load->view('BACKEND/ajax_updateStatus', $update);
   }

   public function admincp_ajaxUpdateNoibat() {
      if ($this->input->post('status') == 0) {
         $status = 1;
      } else {
         $status = 0;
      }
      $data = array(
          'noibat' => $status
      );
      $this->db->where('id', $this->input->post('id'));
      $this->db->update(PREFIX . $this->table, $data);

      $update = array(
          'status' => $status,
          'id' => $this->input->post('id'),
          'module' => $this->module
      );
      $this->load->view('BACKEND/ajax_updateNoibat', $update);
   }
  
     public function admincp_ajaxUpdateWinner() {
        $perm = modules::run('admincp/chk_perm', $this->session->userdata('ID_Module'), 'w', 1);
        if ($perm == 'permission-denied') {
            print '<script type="text/javascript">show_perm_denied()</script>';
            $winner = $this->input->post('winner');
            $data = array(
                'winner' => $winner
            );
        } else {
            if ($this->input->post('winner') == 0) {
                $winner = 1;
            } else {
                $winner = 0;
            }
            $data = array(
                'winner' => $winner
            );
            modules::run('admincp/saveLog', $this->module, $this->input->post('id'), 'winner', 'update', $this->input->post('winner'), $winner);
            $this->db->where('id', $this->input->post('id'));
            $this->db->update(PREFIX . $this->table, $data);
        }

        $update = array(
            'winner' => $winner,
            'id' => $this->input->post('id'),
            'module' => $this->module
        );
        $this->load->view('BACKEND/ajax_updateWinner', $update);
    }
     public function admincp_export() {
        $data = array(
            'module' => $this->module
        );
        $this->template->write_view('content', 'BACKEND/ajax_export',$data);
        $this->template->render();
    }
    public function admincp_export_excel() {
        ini_set('memory_limit','300M');
        $date_start = $this->input->post("datestart");
        $date_end = $this->input->post("dateend");
        $contest = $this->model->getContentContest($date_start,$date_end);

        $html_top = '
        <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
        Zhtml xmlns="http://www.w3.org/1999/xhtml">
        <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        </head>
        <body>
        <table width="1191" cellpadding="0" cellspacing="0" border="1" style="font-size:12px;">';
        $n=1;
        $html = '';
        $html_bot = '
        </table>
        </body>
        </html>';
        $report = $contest;
        $filename ='contest_report';
        $html .='
            <tr height="20">
            <td height="20" align="right">'.'STT'.'</td>
            <td>'.'User Name'.'</td>
            <td>'.'Email'.'</td>
            <td>'.'FB_ID'.'</td>
            <td>'.'Times'.'</td>
            <td>'.'Weeks'.'</td>
            <td>'.'Created'.'</td>
            </tr>';
        if($report){
            foreach ($report as $item) {
               
                $html .='
                <tr height="20">
                <td height="20" align="right">'.$n.'</td>
                <td>'.$item->username.'</td>
                <td>'.$item->email.'</td>
                <td>'.$item->fb_id.'</td>
                <td>'.load_diem($item->time).'</td>
                <td>'.$item->week_id.'</td>
                <td>'.$item->created.'</td>
                </tr>';
                $n++;
            }
        }    
        
        header("Content-type: application/x-www-form-urlencoded\r\n" );
        header('Content-Disposition: attachment; filename="'.$filename.'.xls"');
        echo $html_top.$html.$html_bot;
    }
   /* ------------------------------------ End Admin Control Panel -------------------------------- */

   function index() {

        $fb_id = $_SESSION['fb_id'];

        $check = $this->model->check_user($fb_id);
        if($check < 1 )
        {
            $this->model->insert_user();
        }
        $data= array(
            'fb_id' => md5($fb_id)
        );
        $this->template->write_view('content', 'FRONTEND/landing',$data);
        $this->template->render(); 
      
   }
   
   
   public function get_contest()
   {
       $action = trim($this->input->get_post('action'));
     
       switch($action)
       {
            case 'start-game':
                $this->start_game();
                break;
            case 'insert-score':
                $this->end_game();
                break;
			case 'list-win':
				$this->list_win();
				break;	
            case 'top5':
				$this->list_top_day();
				break;	
            case 'player-info':
				$this->player_info();
				break;	
            case 'list-weeks':
				$this->list_weeks();
				break;	
            case 'upload-wall':
				$this->upload_wall();
				break;			
					
       }
   }
   function start_game(){
		$t=time();
        $fb_id = $_SESSION['fb_id'];
		$_SESSION['start'] = $t;
        $key=md5($fb_id);
        $_SESSION['key'] = $key;
        //$week_id=$this->model->get_weeks();
        //$check = $this->model->check_luot_choi_week($fb_id,$week_id[0]->id);
        //if($check > 0)
        //{
            //$this->model->update_status($fb_id,$week_id[0]->id);
        //}
		header_xml();
            echo "<key>".md5($fb_id)."</key>";
			echo "<starttime>".$t."</starttime>";
		footer_xml();
   }
   function player_info()
   {
     $week_id=$this->model->get_weeks();
     $u=$_SESSION['profile'];
     
     $check_luot_choi = $this->model->check_luot_choi($u['id'],$week_id[0]->id);
     
     header_xml();
     if($check_luot_choi >= 3){
           echo "<play3>".'true'."</play3>";
     }
     else
     {
         echo "<play3>".'false'."</play3>";
     }
     footer_xml();
   }
   function end_game(){
        $end=time();
		$week_id=$this->model->get_weeks();
        $start=$_SESSION['start'];
        $ss_key=$_SESSION['key'];
     
    
        $time1 = $this->input->post("t1");
        $time2 = $this->input->post("t2");
        $time3 = $this->input->post("t3");
        
        $mili1 = $this->input->post("m1");
        $mili2 = $this->input->post("m2");
        $mili3 = $this->input->post("m3");
        
        
        $time_game1 = get_time($time1,$mili1);
        $time_game2 = get_time($time2,$mili2);
        $time_game3 = get_time($time3,$mili2);
        
       
        $key2=md5($ss_key.$time1.$start.$time2.'climax13'.$time3).md5($mili1.'123$9839#@4qwert%^yui0993&98389climax13'.$mili2.$mili3);
      
        $key=$this->input->post('a');
       	$u=$_SESSION['profile'];
  
        $user_data = $this->model->get_user($u['id']);
      
       	header_xml();

	
 	    if($key==$key2){
 	      
 	         $insert=array(
    				'user_id'=>$user_data[0]->id,
                    'fb_id'=>$u['id'],  
    				'week_id'=>$week_id[0]->id,
                    'time'=>$time_game1 +  $time_game2 + $time_game3,
    				'status'=>1,
    				'created'=>date('Y-m-d H:i:s'),
                    'ip' =>getIP()
                    
			     );
               $contest_id=$this->model->insert_id('contest',$insert);
               $this->model->save_contest_log($user_data[0]->id,$time_game1,$u['id'],$week_id[0]->id,'game1',$contest_id);
               $this->model->save_contest_log($user_data[0]->id,$time_game2,$u['id'],$week_id[0]->id,'game2',$contest_id);
               $this->model->save_contest_log($user_data[0]->id,$time_game3,$u['id'],$week_id[0]->id,'game3',$contest_id);
               
              echo "<status>true</status>";
		}else{
            
			echo "<status>false</status>";
		}
		footer_xml();
        
	}
   public function list_weeks()
   {
         $weeks = $this->model->get_list_weeks();
         header_xml();
    		if(!empty($weeks))
    		{
    			
    			foreach($weeks as $dt)
    			{
    			   echo '<weeks>';
    			   echo '<active>' . "<![CDATA[" . $dt->active . "]]>" . '</active>';
    			   echo '<id>' . "<![CDATA[" . $dt->id . "]]>" . '</id>';
    			   echo '<name>' . "<![CDATA[" . $dt->name . "]]>" . '</name>';
    			   echo '<time>' . "<![CDATA[" . date('d/m', strtotime($dt->datestart)) .' - '. date('d/m', strtotime($dt->dateend)). "]]>" . '</time>';
    			   echo '</weeks>';	
    			}
    		}
                      
         footer_xml();
   }
   public function list_win()
   {

     
      $data_weeks = $this->model->winner_weeks();
   
  
      header_xml();
		if(!empty($data_weeks))
		{
			
			foreach($data_weeks as $dt)
			{
			 
               $data = $this->model->list_winner_weeks($dt->week_id) ;
               $detail_weeks = $this->model->detail_weeks($dt->week_id);
               echo '<week active="'.$detail_weeks[0]->active.'">';
               echo '<title>' . "<![CDATA[" . date('d/m', strtotime($detail_weeks[0]->datestart)) .' - '. date('d/m', strtotime($detail_weeks[0]->dateend)) . "]]>" . '</title>';
               echo '<id>' . "<![CDATA[" . $detail_weeks[0]->id . "]]>" . '</id>';
               if(!empty($data))
		       {
			
			         foreach($data as $dt)
			         {
                               echo '<item>';
                			   echo '<user>' . "<![CDATA[" . $dt->username . "]]>" . '</user>';
                			   echo '<time>' . "<![CDATA[" . load_phut_giay($dt->time). "]]>" . '</time>';
                               echo '<timem>' . "<![CDATA[" . load_mili_giay($dt->time). "]]>" . '</timem>';
                               echo '</item>';
                     }
                     
                }
                echo '</week>';
			
				
			}
		}
                  
        footer_xml();
   } 
   public function list_top_day()
   {

      $data = $this->model->list_top_score_day();
      $top_rating = $this->model->ran_top_score();
    
      $u=$_SESSION['profile'];
      $user_data = $this->model->get_user($u['id']);
      $i = 1;
      $rating = 0;
      $total_time = "";
      if(!empty($top_rating))
      {
			foreach($top_rating as $dt)
			{
			  if($dt->fb_id == $u['id'])
              {
                $rating  = $i;
                $total_time = load_phut_giay($dt->time);
              }
              $i++;
            }
      }
     
      header_xml();
       echo '<rating>' . $rating . '</rating>';
       echo '<totaltime>' . $total_time . '</totaltime>';
		if(!empty($data))
		{
			foreach($data as $dt)
			{
               echo '<item>';
			   echo '<user>' . "<![CDATA[" . $dt->username . "]]>" . '</user>';
		       echo '<time>' . "<![CDATA[" . load_phut_giay($dt->time).":".load_mili_giay($dt->time). "]]>" . '</time>';
               
               echo '</item>';
			}
		}
                  
        footer_xml();
   } 
   public function upload_wall()
   {
     require 'application/libraries/facebook.php';
     $facebook = new Facebook(array('appId'  => FB_APP_ID, 'secret' => FB_SECRET));
     $user_id = $facebook->getUser();
     $signed_request = $facebook->getSignedRequest();
     $facebook->api('me/feed/', 'POST', array(
        'message' => 'Nhanh tay lẹ mắt cùng Opera',
        'name' => 'Nhanh tay lẹ mắt cùng Opera',
        'description' => 'Hãy nhanh tay lẹ mắt để săn những giải thưởng hấp dẫn từ Opera, Còn chờ gì nữa,tham gia ngay',
        'caption' => 'Nhanh tay lẹ mắt cùng Opera',
        'picture' => PATH_URL.'static/images/share_facebook.png',
        'link' => 'http://apps.facebook.com/492665260827371/'
    ));
   }
   public function save_image()
   {
        $fb_id = $_SESSION['fb_id'];
        $file = uniqid(rand(1000000, 10000000));
        $img = file_get_contents('php://input');
        $filename = APPPATH.'../static/uploads/contest/' .$fb_id.$file.'.jpg';
        file_put_contents($filename, $img);
        $file_name = $fb_id.$file.'.jpg';
        echo  $file_name;
   }

    public function save_image_wall()
   {
        $fb_id = $_SESSION['fb_id'];
        $file = uniqid(rand(1000000, 10000000));
        $img = file_get_contents('php://input');
        $filename = APPPATH.'../static/uploads/upload_wall/' .$fb_id.$file.'abc.jpg';
        file_put_contents($filename, $img);
        $file_name = $fb_id.$file.'abc'.'.jpg';
        echo  $file_name;
   }
   
    public function update_thumb_default()
    {
        $result = $this->model->list_contest_new();
        foreach($result as $r){
            $data = array(
                'thumb' =>$r->thumb_default
            );
            $this->db->where('id', $r->id);
            $this->db->update('cli_contest', $data); 
        }
    }
    public function save_image_avt($fb_id)
    {
        
        
        $file_name =$fb_id.'.jpg';
	    $file_new =BASE_UPLOAD_AVATAR.$file_name;
        $in=    fopen('https://graph.facebook.com/'.$fb_id.'/picture?type=large', "rb");
        $out=   fopen($file_new, "wb");
        while ($chunk = fread($in,8192))
        {
	        fwrite($out, $chunk, 8192);
	    }
	    fclose($in);
	    fclose($out);

        return $file_name;
        
     
    }public function save_image_avatar($fb_id)
    {
        
        
        $profile= $this->model->get_profile($fb_id);
        header_xml();
            echo  "<image>". PATH_URL.'static/uploads/avatar/'.$profile[0]->avatar. "</image>";
        footer_xml();
     
    }
    public function upload_images_from_link() {
            $url= $this->input->get_post("linkimg");
    
            $tmp = explode("/",$url);
        	$file = $tmp[count($tmp) - 1];
            $file = str_replace("%","-",$file);
            
        	//echo $url."<br/>";
        	if($file)
        	{
        		
        			$h = @fopen("$url","rb");
        			$content = '';
        			if($h)
        			{
        				while(!feof($h))
        				{
        					$buffer = fgets($h, 1024);
        					$content .= $buffer;
        				}
        				fclose($h);
        			}
        			$f = fopen(BASE_UPLOAD.$file,'w');
        			fwrite($f,$content);
        			fclose($f);
        			$ff = fopen(BASE_UPLOAD.$file,'w');
        			fwrite($ff,$content);
        			fclose($ff);
                    header_xml();
                        echo '<link>'.PATH_IMAGE.'contest_tmp/' .$file.'</link>';
                    footer_xml();
        	
        	}
        	else
        	{
        		 header_xml();
                        echo '<link>edf</link>';
                 footer_xml();
        	}
                    
        }
		


}